package com.example.onlinemallsystem.service.impl;

import com.example.onlinemallsystem.entity.User;
import com.example.onlinemallsystem.mapper.UserMapper;
import com.example.onlinemallsystem.service.UserService;
import com.example.onlinemallsystem.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/** 用户模块业务层的实现类 */
@Service // 将当前类对象交给Spring来管理，自动创建对象以及对对象的维护
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void insert(User user) {
        userMapper.insert(user);
    }

    @Override
    public void reg(User user) throws UsernameDuplicatedException, InsertException {
        // 通过user参数获取传递过来的username
        String username = user.getUsername();
        // 通过findByUsername（username）判断是否注册过
        User result = userMapper.findByUsername(username);
        // 判断结果集是否为null 不为null 抛异常
        if (result != null) {
            throw new UsernameDuplicatedException(username + "用户名被占用");
        }

        // 密码加密处理
        String oldPassword = user.getPassword();
        // 生成盐值
        String salt = UUID.randomUUID().toString().toUpperCase();
        // 将密码和盐值作为一个整体进行加密
        String md5Password = getMD5password(oldPassword, salt);

        // 将加密后的密码和盐值设置到user对象中
        user.setPassword(md5Password);
        user.setSalt(salt);

        // 补全数据：isDelete设置为0
        user.setDeleted(0);

        // 补全日志信息
        Date now = new Date();
        user.setCreateTime(now);  // 修改为createdTime与数据库字段一致
        user.setUpdateTime(now);  // 修改为modifiedTime与数据库字段一致
        user.setUpdateUser(username);  // 添加modifiedUser字段

        // 执行注册功能(rows==1)
        System.out.println("准备插入用户"+user);
        Integer rows = userMapper.insert(user);
        if (rows != 1) {
            throw new InsertException("用户注册过程中产生了未知的异常");
        }
    }

    @Override
    public User login(String username, String password, String userType)
            throws UserNotFoundException, PasswordNotMatchException {

        // 1. 根据用户名查询用户数据
        User result = userMapper.findByUsername(username);

        // 2. 判断用户是否存在
        if (result == null) {
            throw new UserNotFoundException("用户未注册");
        }

        // 3. 判断用户是否被删除
        if (result.getDeleted() == 1) {
            throw new UserNotFoundException("用户已删除");
        }

        // 4. 验证密码是否正确
        String oldPassword = result.getPassword();
        String salt = result.getSalt();
        String newMd5Password = getMD5password(password, salt);

        if (!newMd5Password.equals(oldPassword)) {
            throw new PasswordNotMatchException("用户密码错误");
        }

        User user = new User();
        user.setId(result.getId());
        user.setUsername(result.getUsername());
        user.setUserType(result.getUserType());

        return user;
    }

    // 辅助方法：将英文用户类型转为中文描述
    public String getUserTypeName(String userType) {
        if (userType == null) return "未知";
        switch (userType.toLowerCase()) {
            case "buyer":
                return "买家";
            case "seller":
                return "卖家";
            case "admin":
                return "管理员";
            default:
                return userType;
        }
    }

    // MD5加密方法
    public String getMD5password(String password, String salt) {
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes());
        }
        return password;
    }

    @Override
    public User getById(Long id) {
        User result = userMapper.findById(id);
        if (result == null) {
            throw new UserNotFoundException("用户数据不存在");
        }

        if (result.getDeleted().equals(1)) {
            // 是：抛出UserNotFoundException异常
            throw new UserNotFoundException("用户数据不存在");
        }

        // 创建新的User对象
        User user = new User();

        user.setId(result.getId());
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setDeleted(result.getDeleted());
        user.setAddress(result.getAddress());

        return user;
    }


    @Override
    public void changeInfo( User user) {
        // 调用userMapper的findById()方法，根据参数id查询用户数据
        userMapper.updateInfoById(user);
        // 判断查询结果是否为null
        if (user == null) {
            throw new UserNotFoundException("用户数据不存在");
        }

        if (user.getDeleted().equals(1)) {
            // 是：抛出UserNotFoundException异常
            throw new UserNotFoundException("用户数据不存在");
        }

        // 向参数user中补全数据
        user.setId(user.getId());
        user.setStatus(user.getStatus());
        user.setUsername(user.getUsername());
        user.setUpdateTime(new Date());
        user.setUpdateUser(user.getUsername());
        Integer rows = userMapper.updateInfoById(user);
        // 判断以上返回的受影响行数是否不为1
        if (rows != 1) {
            throw new UpdateException("更新用户数据时出现未知错误，请联系系统管理员");
        }


    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.findAllUsers();
    }

    @Override
    public void deleteUser(Long id) {
        // 检查用户是否存在
        User user = userMapper.findById(id);
        if (user == null) {
            throw new UserNotFoundException("用户不存在");
        }

        // 检查是否为管理员，不允许删除管理员
        if ("admin".equals(user.getUserType())) {
            throw new RuntimeException("不能删除管理员用户");
        }

        // 软删除用户
        Integer rows = userMapper.deleteById(id);
        if (rows != 1) {
            throw new DeleteException("删除用户失败");
        }
    }
}

